package com.example.mynewsapp.fragment

import android.app.Activity
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.example.mynewsapp.R
import com.example.mynewsapp.network.ApiInterface
import com.example.mynewsapp.network.Constants
import com.example.mynewsapp.network.HttpRequest
import com.example.mynewsapp.util.Utils.getCountry
import kotlinx.android.synthetic.main.fragment_weather.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import androidx.fragment.app.Fragment
import com.example.mynewsapp.fragment.Fragment.mActivity
import com.example.mynewsapp.model.WeatherModel
import com.example.mynewsapp.model.WeatherPage
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import com.example.mynewsapp.network.Constants.DATE_FORMAT
import com.example.mynewsapp.network.Constants.DATE_FORMAT_1
import com.example.mynewsapp.network.Constants.UNITS
import com.example.mynewsapp.network.Constants.WEATHER_KEY
import kotlinx.android.synthetic.main.fragment_weather.down_pull_update
import kotlinx.android.synthetic.main.news_view.*
import java.text.SimpleDateFormat
import java.util.*

class FragmentWeather : Fragment() {

    var keywords :String = ""

    var icon = ""
    var date = ""
    var temperature = ""
    var city = ""
    var image = 0
    var lang = ""

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_weather, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        imageClear.setOnClickListener {
            etSearchView.getText().clear()
        }

    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        search_title.setText(R.string.weather)

        init()

        down_pull_update.setColorSchemeResources(R.color.colorPrimaryDark)
        down_pull_update.setOnRefreshListener {
            var handler = Handler()
            handler.postDelayed({
                getWeatherData()
                down_pull_update.isRefreshing = false
                refreshSuccess()
            }, 1000)
        }

        etSearchView.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                keywords = etSearchView.getText().toString()
                if (keywords.isEmpty()) {
                    Toast.makeText(context, getString(R.string.searchTips), Toast.LENGTH_SHORT).show()
                } else {
                    getWeatherData()
                }
                val inputManager = v.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                inputManager.hideSoftInputFromWindow(v.windowToken, 0)
                return@OnEditorActionListener true
            }
            false
        })
    }

    private fun init() {
        keywords = "dongguan"
        getWeatherData()
    }

    private fun getWeatherData(){

        if (keywords == "") return

        if (getCountry()=="cn") lang = "zh_cn"
        else lang = "en"

        val apiInterface = HttpRequest.createApi(Constants.BASE_WEATHER_URL).create(ApiInterface::class.java)
        val call = apiInterface.getWeather(keywords,UNITS,WEATHER_KEY,lang)
        call.enqueue(object : Callback<WeatherModel> {
            @RequiresApi(Build.VERSION_CODES.O)
            override fun onResponse(call: Call<WeatherModel>, response: Response<WeatherModel>) {
                if (response.isSuccessful && response.body() != null) {
                    icon = "https://openweathermap.org/img/wn/${response.body()!!.weather[0].icon}@2x.png"
                    date = SimpleDateFormat(DATE_FORMAT_1,Locale.getDefault()).format(Date())
//                    date = LocalDateTime.now().format(DateTimeFormatter.ofPattern(DATE_FORMAT_1))
                    temperature = response.body()!!.main.temp.toString()
                    city = response.body()!!.name + ", " + response.body()!!.sys.country
                    when (response.body()!!.weather[0].icon) {
                        "01d","01n","02d","02n","03d","03n","04d","04n" -> image = R.drawable.sunny_day
                        "09d","09n","10d","10n","11d","11n" -> image = R.drawable.raining
                        "13d","13n" -> image = R.drawable.snowfalling
                        "50d","50n" -> image = R.drawable.mistday
                    }

                    var item = WeatherPage(icon,date,temperature,city,image)
                    onSetWeather(item)
                }
            }
            override fun onFailure(call: Call<WeatherModel>, t: Throwable) {
                tips()
            }
        })
    }

    private fun onSetWeather(item:WeatherPage){
        if (item.icon == null) {
            weather_icon.setImageResource(R.drawable.ic_broken_image)
        } else {
            context?.let {
                Glide.with(it)
                    .load(item.icon)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(weather_icon)
            }
        }
        weather_date.text = item.date
        weather_temperature.text = item.temperature
        weather_city.text = item.city
        weather_image.setImageResource(item.image)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mActivity = context as Activity
    }

    private fun tips() {
        if (this.isAdded){
            Toast.makeText(mActivity, getString(R.string.searchNothing), Toast.LENGTH_SHORT).show()
        }
    }

    private fun refreshSuccess () {
        if (this.isAdded){
            Toast.makeText(mActivity, getString(R.string.refreshSuccess), Toast.LENGTH_SHORT).show()
        }
    }

}